<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\console\input\Argument;
use think\facade\App;

class MakeRoute extends Command
{
    protected function configure()
    {
        $this->setName('make:route')
            ->addArgument('name', Argument::REQUIRED, '路由名称（对应控制器模块）')
            ->addOption('module', null, Option::VALUE_REQUIRED, '模块名称，默认为 app');
    }

    protected function execute(Input $input, Output $output)
    {
        $name = $input->getArgument('name');
        $module = $input->getOption('module');

        // 路由小写命名
        $routeName = strtolower($name);
        $controllerName = $name;

        // 模板路径
        $stubPath = App::getAppPath() . 'command' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'route.tpl';

        if (!file_exists($stubPath)) {
            $output->writeln("<error>路由模板文件不存在</error>");
            return;
        }

        $content = file_get_contents($stubPath);

        // 替换变量
        $content = str_replace(
            ['{{$routeName}}', '{$controllerName}'],
            [$routeName, $controllerName],
            $content
        );

        // 写入目标文件
        if (!empty($module)) {
            $routePath = app_path() . "{$module}/route/{$routeName}.php";
        } else {
            $routePath = root_path() . "route/{$routeName}.php";
        }

        if (!is_dir(dirname($routePath))) {
            mkdir(dirname($routePath), 0755, true);
        }
        file_put_contents($routePath, $content);

        $output->writeln("路由 {$routeName} 已生成");
    }
}
